﻿using System;
using System.IO;

namespace yunio
{
    public enum YunioDataType : ushort
    {
        Unknown = 0,
        Binary = 1,
        Text = 2,
        Json = 3,
        Xml = 4,
    }
    public class YunioData
    {
        internal YunioDataType _type;
        internal YunioJson json { get; set; }
        internal YunioXml xml { get; set; }
        internal string text { get; set; }
        internal Stream binary { get; set; }
        internal object obj { get; set; }

        internal YunioData() { }
        internal YunioData(object data)
        {
            switch (data)
            {
                case string _text:
                    if ((_text.StartsWith("{") && _text.EndsWith("}")) || _text.StartsWith("[") && _text.EndsWith("]"))
                    {
                        var _text_json = new YunioJson(_text);
                        if (_text_json.OK)
                        {
                            _type = YunioDataType.Json;
                            json = _text_json;
                            break;
                        }
                    }
                    _type = YunioDataType.Text;
                    text = _text;
                    break;
                case YunioJson _json:
                    _type = YunioDataType.Json;
                    json = _json;
                    break;
                case YunioXml _xml:
                    _type = YunioDataType.Xml;
                    xml = _xml;
                    break;
                case Stream _binary:
                    _type = YunioDataType.Binary;
                    binary = _binary;
                    break;
                default:
                    _type = YunioDataType.Unknown;
                    obj = data;
                    break;
            }
        }

        public static YunioData New(object data)
        {
            try
            {
                return new YunioData(data);
            }
            catch
            {
                var d = new YunioData();
                d._type = YunioDataType.Unknown;
                d.obj = data;
                return new YunioData(d);
            }
        }
        public YunioDataType DataType { get { return _type; } }
        public YunioJson Json { get { return json; } }
        public YunioXml Xml { get { return xml; } }
        public string Text { get { return text; } }
        public Stream Binary { get { return binary; } }
    }
}
